package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.pojo.*;
import com.example.demo.service.LegendService;
import com.example.demo.service.SkinService;
import com.example.demo.util.LegendDetailUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController()
@CrossOrigin
public class LegendController {
    @Autowired
    private LegendService legendService;



    @Autowired
    private LegendDetailUtil legendDetailUtil;

    @Value("${minio.legendPhotoUrl}")
    private String legendPhotoUrl;

    @Value("${minio.skinUrl}")
    private String skinUrl;


    @Autowired
    private SkinService skinService;

    @GetMapping("/getAllLegends")
    public R<List<Legend>> getAllLegends(){
        return  R.success(legendService.getAllLegends());
    }


    @PostMapping("/getLegendsByName")
    public  R getLegendsByName(@RequestParam String  legendName,@RequestParam Integer pageNo,@RequestParam Integer pageSize){
        Map map=new HashMap();
        Page<Legend> page=new Page<Legend>(pageNo,pageSize);
        QueryWrapper<Legend> qw=new QueryWrapper<>();

        qw.like(legendName!=null,"legend_name",legendName);
        qw.orderByAsc("legend_id");

        List<Legend> legend = legendService.page(page, qw).getRecords();
        List<LegendWithUrl> legends=new ArrayList<>();
        for (Legend legend1 : legend) {
            LegendWithUrl lwu=new LegendWithUrl();
            BeanUtils.copyProperties(legend1,lwu);
            lwu.setLegendPhotoUrl(legendPhotoUrl+lwu.getLegendId()+".png");
            legends.add(lwu);

        }
        map.put("legend",legends);
        map.put("total",page.getTotal());
        return R.success(map);

    }
    @PostMapping("/getLegendDetail")
    public R getPhoto(@RequestParam("legendId") Integer legendId){

        LegendDetail legendDetail = new LegendDetail();
        QueryWrapper<Legend> qw=new QueryWrapper<>();
        qw.lambda().eq(Legend::getLegendId,legendId);
        Legend legend = legendService.getOne(qw);
        System.out.println(legend);
        LegendDetail legendDetail1 = legendDetailUtil.setALll(legend, legendDetail);

        QueryWrapper<Skin> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(Skin::getLegendId,legendId);
        List<Skin> skins =skinService.list(queryWrapper);
        for (Skin skin : skins) {
            skin.setSkinUrl(skinUrl+skin.getLegendId()+"/"+skin.getLegendId()+skin.getSkinName()+".png");
        }
        legendDetail.setSkin(skins);
        System.out.println(legendDetail);
        return R.success(legendDetail);
    }
}
